import { useState } from 'react'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism'
import './App.css'

// 动态导入curlconverter以避免ES模块问题
let curlconverter = null
const loadCurlConverter = async () => {
  if (!curlconverter) {
    try {
      curlconverter = await import('curlconverter')
    } catch (error) {
      console.error('无法加载curlconverter:', error)
      throw new Error('curlconverter库加载失败，请刷新页面重试')
    }
  }
  return curlconverter
}

function App() {
  const [curlCommand, setCurlCommand] = useState('')
  const [targetLanguage, setTargetLanguage] = useState('python')
  const [convertedCode, setConvertedCode] = useState('')
  const [error, setError] = useState('')

  // 支持的语言列表 - 使用动态加载的curlconverter API
  const languages = [
    { value: 'python', label: 'Python (requests)' },
    { value: 'javascript', label: 'JavaScript (fetch)' },
    { value: 'nodejs', label: 'Node.js (axios)' },
    { value: 'go', label: 'Go' },
    { value: 'php', label: 'PHP (cURL)' },
    { value: 'java', label: 'Java (HttpClient)' },
    { value: 'rust', label: 'Rust' },
    { value: 'ruby', label: 'Ruby' },
    { value: 'swift', label: 'Swift' },
    { value: 'csharp', label: 'C#' }
  ]

  // 示例 curl 命令
  const examples = [
    {
      name: 'Simple GET',
      command: 'curl https://api.github.com/users/octocat'
    },
    {
      name: 'POST with JSON',
      command: 'curl -X POST https://httpbin.org/post -H "Content-Type: application/json" -d \'{"name": "John", "age": 30}\''
    },
    {
      name: 'With Headers & Cookies',
      command: 'curl -H "Authorization: Bearer token123" -H "Accept: application/json" -b "session_id=abc123; user_pref=dark_mode" https://api.example.com/data'
    },
    {
      name: 'Form Data with Auth', 
      command: 'curl -X POST https://httpbin.org/post -u "username:password" -d "title=My Document" -d "category=docs"'
    },
    {
      name: 'Complex JSON + Cookies',
      command: `curl 'https://www.ynlaw.cn/api/get_comp' -H 'content-type: application/json;charset=UTF-8' -b 'sajssdk_2015_cross_ZQSensorsObjnew_user=1' --data-raw '{"view": "LawyerTeam", "compId": "c_static_001_P_51230-17243991258670"}'`
    }
  ]

  const handleConvert = async () => {
    try {
      setError('')
      if (curlCommand.trim() && targetLanguage) {
        // 动态加载curlconverter
        const converter = await loadCurlConverter()
        
        // 根据选择的语言调用对应的API
        let result = ''
        switch (targetLanguage) {
          case 'python':
            result = converter.toPython(curlCommand)
            break
          case 'javascript':
            result = converter.toJavaScript(curlCommand)
            break
          case 'nodejs':
            result = converter.toNodeAxios(curlCommand)
            break
          case 'go':
            result = converter.toGo(curlCommand)
            break
          case 'php':
            result = converter.toPhp(curlCommand)
            break
          case 'java':
            result = converter.toJava(curlCommand)
            break
          case 'rust':
            result = converter.toRust(curlCommand)
            break
          case 'ruby':
            result = converter.toRuby(curlCommand)
            break
          case 'swift':
            result = converter.toSwift(curlCommand)
            break
          case 'csharp':
            result = converter.toCSharp(curlCommand)
            break
          default:
            result = converter.toPython(curlCommand)
        }
        
        setConvertedCode(result)
      } else {
        setConvertedCode('')
      }
    } catch (err) {
      setError('转换失败: ' + err.message)
      setConvertedCode('')
    }
  }

  // 输入变化时自动转换
  const handleInputChange = (value) => {
    setCurlCommand(value)
    // 延迟转换，避免频繁操作
    if (value.trim()) {
      const timeoutId = setTimeout(async () => {
        try {
          setError('')
          // 动态加载curlconverter
          const converter = await loadCurlConverter()
          
          // 根据选择的语言调用对应的API
          let result = ''
          switch (targetLanguage) {
            case 'python':
              result = converter.toPython(value)
              break
            case 'javascript':
              result = converter.toJavaScript(value)
              break
            case 'nodejs':
              result = converter.toNodeAxios(value)
              break
            case 'go':
              result = converter.toGo(value)
              break
            case 'php':
              result = converter.toPhp(value)
              break
            case 'java':
              result = converter.toJava(value)
              break
            case 'rust':
              result = converter.toRust(value)
              break
            case 'ruby':
              result = converter.toRuby(value)
              break
            case 'swift':
              result = converter.toSwift(value)
              break
            case 'csharp':
              result = converter.toCSharp(value)
              break
            default:
              result = converter.toPython(value)
          }
          
          setConvertedCode(result)
        } catch (err) {
          setError('转换失败: ' + err.message)
          setConvertedCode('')
        }
      }, 500) // 500ms 延迟
      
      return () => clearTimeout(timeoutId)
    } else {
      setConvertedCode('')
      setError('')
    }
  }

  // 语言变化时自动转换
  const handleLanguageChange = async (newLanguage) => {
    setTargetLanguage(newLanguage)
    if (curlCommand.trim()) {
      try {
        setError('')
        // 动态加载curlconverter
        const converter = await loadCurlConverter()
        
        // 根据选择的语言调用对应的API
        let result = ''
        switch (newLanguage) {
          case 'python':
            result = converter.toPython(curlCommand)
            break
          case 'javascript':
            result = converter.toJavaScript(curlCommand)
            break
          case 'nodejs':
            result = converter.toNodeAxios(curlCommand)
            break
          case 'go':
            result = converter.toGo(curlCommand)
            break
          case 'php':
            result = converter.toPhp(curlCommand)
            break
          case 'java':
            result = converter.toJava(curlCommand)
            break
          case 'rust':
            result = converter.toRust(curlCommand)
            break
          case 'ruby':
            result = converter.toRuby(curlCommand)
            break
          case 'swift':
            result = converter.toSwift(curlCommand)
            break
          case 'csharp':
            result = converter.toCSharp(curlCommand)
            break
          default:
            result = converter.toPython(curlCommand)
        }
        
        setConvertedCode(result)
      } catch (err) {
        setError('转换失败: ' + err.message)
        setConvertedCode('')
      }
    }
  }

  const copyToClipboard = async () => {
    const btn = document.querySelector('.copy-btn')
    const originalText = btn.textContent
    
    try {
      // 检查 Clipboard API 是否可用
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(convertedCode)
      } else {
        // 降级方案：使用传统的 execCommand 或创建临时 textarea
        await fallbackCopyTextToClipboard(convertedCode)
      }
      
      // 显示成功提示
      btn.textContent = '✓ 已复制!'
      btn.style.background = '#28a745'
      
      setTimeout(() => {
        btn.textContent = originalText
        btn.style.background = ''
      }, 2000)
    } catch (err) {
      console.error('复制失败:', err)
      // 尝试降级方案
      try {
        await fallbackCopyTextToClipboard(convertedCode)
        btn.textContent = '✓ 已复制!'
        btn.style.background = '#28a745'
        
        setTimeout(() => {
          btn.textContent = originalText
          btn.style.background = ''
        }, 2000)
      } catch (fallbackErr) {
        console.error('降级复制也失败:', fallbackErr)
        btn.textContent = '✗ 复制失败'
        btn.style.background = '#dc3545'
        
        setTimeout(() => {
          btn.textContent = originalText
          btn.style.background = ''
        }, 3000)
        
        // 显示手动复制提示
        showManualCopyDialog(convertedCode)
      }
    }
  }

  // 降级复制方案
  const fallbackCopyTextToClipboard = (text) => {
    return new Promise((resolve, reject) => {
      // 创建临时 textarea 元素
      const textArea = document.createElement('textarea')
      textArea.value = text
      
      // 设置样式使其不可见
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      textArea.style.opacity = '0'
      
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        const successful = document.execCommand('copy')
        document.body.removeChild(textArea)
        
        if (successful) {
          resolve()
        } else {
          reject(new Error('execCommand copy failed'))
        }
      } catch (err) {
        document.body.removeChild(textArea)
        reject(err)
      }
    })
  }

  // 显示手动复制对话框
  const showManualCopyDialog = (text) => {
    const modal = document.createElement('div')
    modal.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;
    `
    
    const dialog = document.createElement('div')
    dialog.style.cssText = `
      background: white;
      padding: 2rem;
      border-radius: 8px;
      max-width: 500px;
      width: 90%;
      max-height: 80%;
      overflow: auto;
    `
    
    dialog.innerHTML = `
      <h3 style="margin-top: 0; color: #333;">📋 手动复制代码</h3>
      <p style="color: #666; margin-bottom: 1rem;">自动复制失败，请手动选择并复制以下代码：</p>
      <textarea readonly style="
        width: 100%;
        height: 200px;
        font-family: monospace;
        font-size: 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 8px;
        resize: vertical;
      ">${text}</textarea>
      <div style="text-align: right; margin-top: 1rem;">
        <button onclick="this.parentElement.parentElement.parentElement.remove()" style="
          background: #6c757d;
          color: white;
          border: none;
          padding: 8px 16px;
          border-radius: 4px;
          cursor: pointer;
        ">关闭</button>
      </div>
    `
    
    modal.appendChild(dialog)
    document.body.appendChild(modal)
    
    // 选中文本
    const textarea = dialog.querySelector('textarea')
    textarea.focus()
    textarea.select()
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        modal.remove()
      }
    })
  }

  const loadExample = async (command) => {
    setCurlCommand(command)
    // 加载示例后自动转换
    try {
      setError('')
      // 动态加载curlconverter
      const converter = await loadCurlConverter()
      
      // 根据选择的语言调用对应的API
      let result = ''
      switch (targetLanguage) {
        case 'python':
          result = converter.toPython(command)
          break
        case 'javascript':
          result = converter.toJavaScript(command)
          break
        case 'nodejs':
          result = converter.toNodeAxios(command)
          break
        case 'go':
          result = converter.toGo(command)
          break
        case 'php':
          result = converter.toPhp(command)
          break
        case 'java':
          result = converter.toJava(command)
          break
        case 'rust':
          result = converter.toRust(command)
          break
        case 'ruby':
          result = converter.toRuby(command)
          break
        case 'swift':
          result = converter.toSwift(command)
          break
        case 'csharp':
          result = converter.toCSharp(command)
          break
        default:
          result = converter.toPython(command)
      }
      
      setConvertedCode(result)
    } catch (err) {
      setError('转换失败: ' + err.message)
      setConvertedCode('')
    }
  }

  const getSyntaxLanguage = () => {
    const syntaxMap = {
      'python': 'python',
      'javascript': 'javascript',
      'nodejs': 'javascript',
      'go': 'go',
      'php': 'php',
      'java': 'java',
      'csharp': 'csharp',
      'rust': 'rust',
      'ruby': 'ruby',
      'swift': 'swift'
    }
    return syntaxMap[targetLanguage] || 'text'
  }

  return (
    <div className="app">
      <header className="header">
        <h1>🔄 Curl Converter</h1>
        <p>将 curl 命令转换为各种编程语言的代码</p>
      </header>

      <main className="main">
        <div className="container">
          {/* 示例命令 */}
          <section className="examples">
            <h3>📝 示例命令</h3>
            <div className="example-buttons">
              {examples.map((example, index) => (
                <button
                  key={index}
                  className="example-btn"
                  onClick={() => loadExample(example.command)}
                >
                  {example.name}
                </button>
              ))}
            </div>
          </section>

          {/* 主工作区域 - 左右布局 */}
          <div className="main-workspace">
            {/* 输入区域 */}
            <section className="input-section">
              <div className="input-header">
                <h3>📥 输入 curl 命令</h3>
                <select
                  value={targetLanguage}
                  onChange={(e) => handleLanguageChange(e.target.value)}
                  className="language-select"
                >
                  {languages.map(lang => (
                    <option key={lang.value} value={lang.value}>
                      {lang.label}
                    </option>
                  ))}
                </select>
              </div>
              <textarea
                value={curlCommand}
                onChange={(e) => handleInputChange(e.target.value)}
                placeholder="粘贴你的 curl 命令..."
                className="curl-input"
                rows={12}
              />
              <div className="input-actions">
                <button onClick={handleConvert} className="convert-btn">
                  🔄 手动转换
                </button>
                <span className="auto-convert-hint">
                  ✨ 输入完成后自动转换
                </span>
              </div>
            </section>

            {/* 输出区域 */}
            <section className="output-section">
              <div className="output-header">
                <h3>📤 转换结果</h3>
              </div>
              
              {error && (
                <div className="error">
                  ❌ {error}
                </div>
              )}
              
              {convertedCode && (
                <div className="code-output">
                  <SyntaxHighlighter
                    language={getSyntaxLanguage()}
                    style={tomorrow}
                    customStyle={{
                      margin: 0,
                      borderRadius: '8px',
                      fontSize: '14px',
                      height: '100%'
                    }}
                  >
                    {convertedCode}
                  </SyntaxHighlighter>
                </div>
              )}
              
              {!convertedCode && !error && (
                <div className="placeholder">
                  ✨ 在左侧输入 curl 命令，结果将在这里显示
                </div>
              )}
              
              {/* 复制按钮放在输出框下方 */}
              {convertedCode && (
                <div className="output-actions">
                  <button onClick={copyToClipboard} className="copy-btn">
                    📋 复制代码
                  </button>
                </div>
              )}
            </section>
          </div>
        </div>
      </main>

      <footer className="footer">
        <p>基于 <a href="https://github.com/curlconverter/curlconverter" target="_blank" rel="noopener noreferrer">curlconverter</a> 构建</p>
      </footer>
    </div>
  )
}

export default App